<?php
/**
 * @Author:      lyt
 * @DateTime:    2016-05-24 14:44:52
 * @Description: 订单的支付记录
 */
class OrderPay extends Eloquent
{
    protected $table = "order_pay_record";

    public static $pay_pay_type=array(
        "1"=>"线下支付现金",
        "2"=>"支付宝",
        "3"=>"微信",
        "5"=>"其他",
        '6'=>'线下支付挂单',
        "7"=>"刷卡",
        '8'=>'余额支付',
        '11'=>'线下支票',
        '20'=>'智能pos',
    );

    public static $pay_pay_type_source=array(
        "1"=>array(1,2),
        '2'=>array(1,2),
        '3'=>array(1,2),
        "5"=>array(1),
        '6'=>array(1),
        "7"=>array(1,2),
        '8'=>array(1),
        '11'=>array(1),
        '20'=>array(2),
    );

    public static $ei_pay_type=array(1,2,3,7,8,11);//记录积分和经验的 支付方式

    /**
     * @Author:      lyt
     * @DateTime:  2017-06-15 17:09:57
     * @Description: 用于撤销一个支付记录
     */
    public static function cancel($order_id,$op_id,$sc_user_id,$create_type){
      return DB::transaction(function () use ($order_id,$op_id,$sc_user_id,$create_type) {
        $order = Orders::where("order_id",$order_id)->lockForUpdate()->first();        
        $op=OrderPay::find($op_id);

        $tran_no = date('YmdHis',time()).Common::generateCode(8);
        //验证完成订单支付
        $o_pu=new OrderPayUndo;
        $o_pu->opr_id=$op_id;
        $o_pu->order_id=$order_id;
        $o_pu->pay_type=$op->pay_type;
        $o_pu->amount=$op->amount;
        $o_pu->status=1;
        $o_pu->create_by=$sc_user_id;
        $o_pu->tran_no=$tran_no;
        $o_pu->create_type=$create_type;
        $o_pu->implement_time=Common::currentTimeString();
        $o_pu->save();
        if($op->sources==2){//如果是调用pos 
        	$wr=WposRecord::where("type",2)->where("buss_id",$op->id)->first();        	
        	$p_r=Pos::statusOrder($wr->id);
		    if($p_r->status==0){
		        // OrderPayUndo::where("opr_id",$op_id)->update(array("status"=>0,"tran_no"=>"","implement_time"=>null));
		        if($p_r->data->trade_status=="REFUND"&&$p_r->data->refund_amount==$op->amount){
			        OrderPayUndo::where("id",$o_pu->id)->update(array("status"=>1,"sources"=>2,"tran_no"=>$tran_no,"implement_time"=>Common::currentTimeString()));
			        $wr->trade_status="REFUND";
			        $wr->pay_info=$p_r->data->pay_info;
			        $wr->return_amont=$op->amount;
			        $wr->save();
			        Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,1,119,$op->amount,'订单支付撤销收入,订单号:'.$order->order_id);
			          //记录用户收入
			        Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,2,219,$op->amount,'订单支付撤销支出,订单号:'.$order->order_id);
			          //记录公司账户支出
			        Account::record_base('1',$tran_no,2,219,$op->amount,'订单支付撤销支出,订单号:'.$order->order_id);
			        OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
			        $op->status=6;
			        $op->save();
			        $order->payable_amount=$order->payable_amount-$op->amount;
			        $order->save();
			        return array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
		        }
	      	}	      	
          	$p_r=Pos::refundOrder($wr->device_en,$wr->cashier_trade_no);
          	if($p_r->status==0){
	            OrderPayUndo::where("id",$o_pu->id)->update(array("status"=>0,"sources"=>2,"tran_no"=>"","implement_time"=>null));
	            OrderPay::where("id",$op_id)->update(array("status"=>7));
          	}else{
          		DB::rollback();
          		$response=Lang::get("scs_error.user_not_car_cancel_error_40117");
          		$response["msg"]=$response["msg"].$p_r->info;
            	return $response;
          	}
        }else{
        	switch ($op->pay_type) {
	          	case 1://银行卡
                case 2://支付宝
                case 3://微信
	          	case 7://现金
	          	case 11://线下支票
	          		Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,1,119,$op->amount,'订单支付撤销收入,订单号:'.$order->order_id);
	                //记录用户收入
	                Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,2,219,$op->amount,'订单支付撤销支出,订单号:'.$order->order_id);
	                //记录公司账户支出
	                Account::record_base('1',$tran_no,2,219,$op->amount,'订单支付撤销支出,订单号:'.$order->order_id);

		            OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
	            	break;
	          	case 8://个人余额 暂时不判断 因为个人 余额现在都为空 新版本判断用户余额
		            $arr=AcountUserRechargeSpend::getUseRecharge($op->id,$op->amount,1);
		                if(sizeof($arr)>0){
		                    foreach ($arr as $_arr) {
			                    //记录了用户消费退款记录
			                    $aurs=new AcountUserRechargeSpendRe;
			                    $aurs->aurr_id=$_arr->aurr_id;
			                    $aurs->user_id=$order->pay_user_id;//谁使用
			                    $aurs->aurr_sp_id=$_arr->id;                      
			                    $aurs->buss_id=$o_pu->id;
			                    $aurs->type=3;//订单支付撤销记录 类型
			                    $aurs->amount=$_arr->user_amount;
			                    $aurs->status=1;
			                    $aurs->tran_no=$tran_no;
			                    $aurs->shop_id=$order->shop_id;
			                    $aurs->implement_time=date("Y-m-d H:i:s",time());
			                    $aurs->save();
			                    //更改充值记录
			                    DB::update('update acount_user_recharge_record set current_amount = current_amount+? where id = ?', array($_arr->user_amount,$_arr->aurr_id));
			                    //更改充值记录消费记录
			                    AcountUserRechargeSpend::where('id',$_arr->id)->update(array('return_amount'=> $_arr->return_amount +$_arr->user_amount,));
			                    //记录个人 各种账户余额
			                    $sac=AcountUserRecharge::find($_arr->aurr_id);
			                    Account::record($order->pay_user_id,$sac->shop_id,$_arr->acount_type,$tran_no,1,119,$_arr->user_amount,'订单支付撤销收入,订单号:'.$order->order_id);
			                    //记录公司账户支出
			                    $base_acount_num=$_arr->acount_type==1?1:3;//如果用的现金账户 计入企业现金帐 如果是虚拟充值记录
			                    Account::record_base($base_acount_num,$tran_no,2,219,$_arr->user_amount,'订单支付撤销支出,订单号:'.$order->order_id);
		                    }
		                    OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
		                }else{
		                    DB::rollback();
		                    $response = Lang::get("scs_error.order_user_notpay_40039");
		                    return $response;
		                } 
	            	break;
	          	case 6://企业挂账
		            Account::record($order->pay_user_id,0,3,$tran_no,1,119,$op->amount,'订单支付撤销收入,订单号:'.$order->order_id);
                	OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
		            break;
	          	default:
		            # code...
		            break;
	        }
	        $op->status=6;
	        $op->save();
	        if($order->user_id==$order->pay_user_id){
	        	$temp_op=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5,7))->first();      
	            if(is_null($temp_op)){//如果没有有未完成的记录
	                $order->pay_user_id=0;//如果客户支付 支付记录都删除或撤销 支付用户重置 
	            }
	        }
	        $order->payable_amount=$order->payable_amount-$op->amount;
	        $order->save();
        }
        return array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
      });

    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-06-23 15:15:32
     * @Description: 用于取消一个撤销中的 记录 也就是取消撤销
     */
    public static function cancelCanceIn($order_id,$op_id,$sc_user_id,$create_type){
      return DB::transaction(function () use ($order_id,$op_id,$sc_user_id,$create_type) {
      	$tran_no = date('YmdHis',time()).Common::generateCode(8);
        $order = Orders::where("order_id",$order_id)->lockForUpdate()->first();        
        $op=OrderPay::find($op_id);        
        if($op->sources==2){//如果是调用pos 
        	$wr=WposRecord::where("type",2)->where("buss_id",$op->id)->first();        	
        	$p_r=Pos::statusOrder($wr->id);
		    if($p_r->status==0){
		        if($p_r->data->trade_status=="REFUND"&&$p_r->data->refund_amount==$op->amount){//如果已经撤销 
			        OrderPayUndo::where("opr_id",$op_id)->update(array("status"=>1,"sources"=>2,"tran_no"=>$tran_no,"implement_time"=>Common::currentTimeString()));
			        $wr->trade_status="REFUND";
			        $wr->pay_info=$p_r->data->pay_info;
			        $wr->return_amont=$op->amount;
			        $wr->save();
			        Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,1,119,$op->amount,'订单支付撤销收入,订单号:'.$order->order_id);
			          //记录用户收入
			        Account::record($order->pay_user_id,$order->shop_id,1,$tran_no,2,219,$op->amount,'订单支付撤销支出,订单号:'.$order->order_id);
			          //记录公司账户支出
			        Account::record_base('1',$tran_no,2,219,$op->amount,'订单支付撤销支出,订单号:'.$order->order_id);
			        OrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
			        $op->status=6;
			        $op->save();
			        if($order->user_id==$order->pay_user_id){
			        	$temp_op=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5,7))->first();      
			            if(is_null($temp_op)){//如果没有有未完成的记录
			                $order->pay_user_id=0;//如果客户支付 支付记录都删除或撤销 支付用户重置 
			            }
			        }
			        $order->payable_amount=$order->payable_amount-$op->amount;
			        $order->save();
			        return array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
		        }else if($p_r->data->trade_status=="PAY"){//说明订单还没撤销
		        	OrderPayUndo::where("opr_id",$op_id)->update(array("status"=>2,"sources"=>2,"tran_no"=>"","implement_time"=>null));
	            	OrderPay::where("id",$op_id)->update(array("status"=>1));
	            	return array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
		        }
	      	}
        }
        return Lang::get("scs_error.order_pay_error_40122");
      });
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-06-23 14:12:00
     * @Description: 用于取消一个支付中的记录
     */
    public static function cancelPayIn($order_id,$op_id){
      return DB::transaction(function () use ($order_id,$op_id) {
        $order = Orders::where("order_id",$order_id)->lockForUpdate()->first();        
        $op=OrderPay::find($op_id);        
        if($op->sources==2){//如果是调用pos 现在只有这一种哦
        	$wr=WposRecord::where("type",2)->where("buss_id",$op->id)->first();        	
        	//查询订单状态
        	$p_r=Pos::statusOrder($wr->id);
		    if($p_r->status==0){ //订单存在
		        if($p_r->data->trade_status=="CLOSED"){//如果交易关闭了
			        $wr->cashier_trade_no=$p_r->data->cashier_trade_no;
		            $wr->mcode=$p_r->data->mcode;
		            $wr->device_en=$p_r->data->device_en;
		            $wr->trade_status=$p_r->data->trade_status;
		            $wr->pay_info=$p_r->data->pay_info;
		            $wr->attach=isset($p_r->data->attach)?$p_r->data->attach:"";
		            $wr->buyer=isset($p_r->data->buyer)?$p_r->data->buyer:"";
		            $wr->thirdSerialNo=isset($p_r->data->thirdSerialNo)?$p_r->data->thirdSerialNo:"";
		            $wr->terminalNo=isset($p_r->data->terminalNo)?$p_r->data->terminalNo:"";
		            $wr->vouchNo=isset($p_r->data->vouchNo)?$p_r->data->vouchNo:"";
		            $wr->batchNo=isset($p_r->data->batchNo)?$p_r->data->batchNo:"";
		            $wr->cardType=isset($p_r->data->cardType)?$p_r->data->cardType:"";
			        $wr->save();			        
			        $op->status=4;
			        $op->save();
			        if($order->user_id==$order->pay_user_id){
			        	$temp_op=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5,7))->first();      
			            if(is_null($temp_op)){//如果没有有未完成的记录
			                $order->pay_user_id=0;//如果客户支付 支付记录都删除或撤销 支付用户重置 
			                $order->save();
			            }
			        }
			        $result = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
		        }else{ //交易其他状态
                    $result = Lang::get("scs_error.order_pay_error_40121");
                }
	      	}elseif($p_r->status==1004){ //订单不存在
		        //查询消息推送情况
                $p_seq = Pos::statusPush($wr->seq_no);
                if($p_seq->status == 0){ //查询成功
                    if($p_seq->data->delivery == 1){ //送达
                        //查询订单状态
                        sleep(11);
                        $p_r=Pos::statusOrder($wr->id);
                        if($p_r->status==0){ //订单存在
                            if($p_r->data->trade_status=="CLOSED"){//如果交易关闭了
                                $wr->cashier_trade_no=$p_r->data->cashier_trade_no;
                                $wr->mcode=$p_r->data->mcode;
                                $wr->device_en=$p_r->data->device_en;
                                $wr->trade_status=$p_r->data->trade_status;
                                $wr->pay_info=$p_r->data->pay_info;
                                $wr->attach=isset($p_r->data->attach)?$p_r->data->attach:"";
                                $wr->buyer=isset($p_r->data->buyer)?$p_r->data->buyer:"";
                                $wr->thirdSerialNo=isset($p_r->data->thirdSerialNo)?$p_r->data->thirdSerialNo:"";
                                $wr->terminalNo=isset($p_r->data->terminalNo)?$p_r->data->terminalNo:"";
                                $wr->vouchNo=isset($p_r->data->vouchNo)?$p_r->data->vouchNo:"";
                                $wr->batchNo=isset($p_r->data->batchNo)?$p_r->data->batchNo:"";
                                $wr->cardType=isset($p_r->data->cardType)?$p_r->data->cardType:"";
                                $wr->save();
                                $op->status=4;
                                $op->save();
                                if($order->user_id==$order->pay_user_id){
                                    $temp_op=OrderPay::where("order_id",$order->order_id)->whereIn("status",array(0,1,5,7))->first();
                                    if(is_null($temp_op)){//如果没有有未完成的记录
                                        $order->pay_user_id=0;//如果客户支付 支付记录都删除或撤销 支付用户重置
                                        $order->save();
                                    }
                                }
                                $result = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
                            }else{ //交易其他状态
                                $result = Lang::get("scs_error.order_pay_error_40121");
                            }
                        }elseif($p_r->status==1004){//订单不存在
                            //关闭订单
                            $op->status=4;
                            $op->save();
                            $result = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order->order_id));
                        }else{
                            $result = Lang::get("scs_error.order_pay_error_40121");
                        }
                    }elseif($p_seq->data->delivery == 0){ //未送达
                        //报警
                        $phones = Config::get('config.notify_phone');
                        $content = '订单['.$order_id.']取消失败，pos订单不存在且推送未送达，请及时处理。';
                        foreach ($phones as $_phone){
                            Sms::send_message('010',$_phone,$content);
                        }
                        $result = Lang::get("scs_error.order_pay_error_40121");
                    }else{
                        //报警
                        $phones = Config::get('config.notify_phone');
                        $content = '订单['.$order_id.']取消失败，pos订单不存在且推送状态未知，请及时处理。';
                        foreach ($phones as $_phone){
                            Sms::send_message('010',$_phone,$content);
                        }
                        $result = Lang::get("scs_error.order_pay_error_40121");
                    }
                }else{ //查询不成功
                    //报警
                    $phones = Config::get('config.notify_phone');
                    $content = '订单['.$order_id.']取消失败，pos订单不存在且推送状态查询失败，请及时处理。';
                    foreach ($phones as $_phone){
                        Sms::send_message('010',$_phone,$content);
                    }
                    $result = Lang::get("scs_error.order_pay_error_40121");
                }
            }else{ //订单其他状态
                $result = Lang::get("scs_error.order_pay_error_40121");
            }
        }
        return $result;
      });
    }
}	